local ffi  = require "ffi"
local zlib = require "zlib"

local function reader(s)
    local done
    return function()
        if done then return end
        done = true
        return s
    end
end

local function writer()
    local t = {}
    return function(data, sz)
        if not data then return table.concat(t) end
        t[#t + 1] = ffi.string(data, sz)
    end
end

local encoding = ngx.req.get_headers()['Content-Encoding']

if encoding == 'gzip' or encoding == 'deflate' or encoding == 'deflate-raw' then
    ngx.req.clear_header('Content-Encoding');
    ngx.req.read_body()

    local body = ngx.req.get_body_data()

    if body then
        local write = writer()
        local map = {
            gzip = 'gzip',
            deflate = 'zlib',
            ['deflate-raw'] = 'deflate'
        }
        local format = map[encoding]
        zlib.inflate(reader(body), write, nil, format)
        ngx.req.set_body_data(write())
    end
end